package com.jhm.ai.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.jhm.ai.domain.AiChatMessage;
import com.jhm.ai.mapper.AiChatMessageMapper;
import com.jhm.ai.service.IAiChatMessageService;
import com.jhm.ai.config.AiConfig;
import com.jhm.ai.domain.ChatRequest;
import com.jhm.ai.util.HttpConnectionManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import java.util.HashMap;

@Service
public class AiChatMessageServiceImpl implements IAiChatMessageService {
    @Autowired
    private AiChatMessageMapper aiChatMessageMapper;

    @Autowired
    private AiConfig aiConfig;

    @Override
    public AiChatMessage selectAiChatMessageById(Long id) {
        return aiChatMessageMapper.selectAiChatMessageById(id);
    }

    @Override
    public List<AiChatMessage> selectAiChatMessageList(AiChatMessage aiChatMessage) {
        return aiChatMessageMapper.selectAiChatMessageList(aiChatMessage);
    }

    @Override
    public int insertAiChatMessage(AiChatMessage aiChatMessage) {
        return aiChatMessageMapper.insertAiChatMessage(aiChatMessage);
    }

    @Override
    public int updateAiChatMessage(AiChatMessage aiChatMessage) {
        return aiChatMessageMapper.updateAiChatMessage(aiChatMessage);
    }

    @Override
    public int deleteAiChatMessageByIds(Long[] ids) {
        return aiChatMessageMapper.deleteAiChatMessageByIds(ids);
    }

    @Override
    public int deleteAiChatMessageById(Long id) {
        return aiChatMessageMapper.deleteAiChatMessageById(id);
    }

    @Override
    public List<AiChatMessage> selectMessagesBySessionId(Long sessionId) {
        return aiChatMessageMapper.selectMessagesBySessionId(sessionId);
    }

    /**
     * 处理SSE聊天消息
     */
    @Override
    public void handleSseChat(ChatRequest chatRequest, String username, String requestId, PrintWriter writer) throws IOException {
        // 保存用户消息
        AiChatMessage userMessage = new AiChatMessage();
        userMessage.setSessionId(chatRequest.getSessionId());
        userMessage.setRole("user");
        userMessage.setType("text");
        userMessage.setMessage(chatRequest.getQuery());
        userMessage.setModeId(chatRequest.getModeId());
        userMessage.setKgId(chatRequest.getKgId());
        userMessage.setCreateBy(username);
        insertAiChatMessage(userMessage);

        // 构建请求参数
        JSONObject params = new JSONObject();
        params.put("query", chatRequest.getQuery());
        params.put("session_id", chatRequest.getSessionId().toString());

        StringBuilder aiResponse = new StringBuilder();
        String url = aiConfig.getHost() + "/chat";
        HttpURLConnection conn = null;

        try {
            URL realUrl = new URL(url);
            conn = (HttpURLConnection) realUrl.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestProperty("Accept", "text/event-stream");
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setConnectTimeout(30000);
            conn.setReadTimeout(0);

            // 存储连接对象
            if (chatRequest.getRequestId() != null) {
                HttpConnectionManager.addConnection(chatRequest.getRequestId(), conn);
            }

            try (PrintWriter out = new PrintWriter(conn.getOutputStream())) {
                out.print(params.toJSONString());
                out.flush();
            }

            int responseCode = conn.getResponseCode();
            if (responseCode != HttpURLConnection.HTTP_OK) {
                try (BufferedReader errorReader = new BufferedReader(
                        new InputStreamReader(conn.getErrorStream(), StandardCharsets.UTF_8))) {
                    StringBuilder errorResponse = new StringBuilder();
                    String line;
                    while ((line = errorReader.readLine()) != null) {
                        errorResponse.append(line);
                    }

                    Map<String, String> errorMap = new HashMap<>();
                    errorMap.put("error", "Server error: " + responseCode);
                    errorMap.put("type", "error");
                    writer.write("data: " + JSONObject.toJSONString(errorMap) + "\n\n");
                    writer.flush();
                    return;
                }
            }

            try (BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8))) {
                String line;
                while ((line = reader.readLine()) != null) {

                    if (line.trim().isEmpty()) continue;

                    if (line.startsWith("data:")) {
                        String data = line.substring(5).trim();
                        if (!data.isEmpty()) {
                            JSONObject jsonData = JSONObject.parseObject(data);
                            
                            if ("content".equals(jsonData.getString("type"))) {
                                String content = jsonData.getString("content");
                                aiResponse.append(content);
                                writer.write("data: " + data + "\n\n");
                                writer.flush();
                            } else if ("done".equals(jsonData.getString("type"))) {
                                // 保存AI回复消息
                                saveAiMessage(chatRequest.getSessionId(), chatRequest.getModeId(),
                                        chatRequest.getKgId(), username, aiResponse.toString());
                                writer.write("data: " + data + "\n\n");
                                writer.flush();
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            String errorMessage = e instanceof java.net.SocketTimeoutException ? "服务器响应超时，请稍后重试" :
                                e instanceof java.net.ConnectException ? "无法连接到服务器，请检查网络" :
                                "服务器繁忙，请稍后重试";
            // 前端主动停止了
            if (e.getMessage().equals("stream is closed")) {
                // 保存AI回复消息
                saveAiMessage(chatRequest.getSessionId(), chatRequest.getModeId(),
                        chatRequest.getKgId(), username, aiResponse.toString());
                HttpConnectionManager.removeConnection(chatRequest.getRequestId());
            } else {
                Map<String, String> errorMap = new HashMap<>();
                errorMap.put("error", errorMessage);
                errorMap.put("type", "error");
                writer.write("data: " + JSONObject.toJSONString(errorMap) + "\n\n");
                writer.flush();
            }
        } finally {
            if (conn != null) {
                conn.disconnect();
            }
        }
    }

    private void saveAiMessage(Long sessionId, Long modelId, Long kgId, String username, String message) {
        AiChatMessage aiMessage = new AiChatMessage();
        aiMessage.setSessionId(sessionId);
        aiMessage.setRole("assistant");
        aiMessage.setType("text");
        aiMessage.setModeId(modelId);
        aiMessage.setKgId(kgId);
        aiMessage.setCreateBy(username);
        aiMessage.setMessage(message);
        insertAiChatMessage(aiMessage);
    }
}
